import { defineStore } from "pinia";
import { MenuState } from "@/store/modulers/menu/types";
import router from "~/router";
import { ElMessageBox } from "element-plus";
import { Menu } from "~/api/system/menu/types";
import { menuTreeToList } from "~/api/util/TreeHelper";

export const useMenuStore = defineStore("icesoft-menu", {
  persist: {
    enabled: true,
  },
  state() {
    const state: MenuState = {
      menu: [],
      defaultActive: undefined,
      openKeys: undefined,
      history: [],
    };
    return state;
  },
  getters: {
    getMenuList() {
      const list = menuTreeToList(this.menu);
      return list;
    },
  },
  actions: {
    refreshMenu(data: any[]) {
      if (data.length === 0) {
        ElMessageBox.confirm(
          "您的授权已过期，请重新登录！",
          "未授权！",
          {
            confirmButtonText: "重新登录",
            showCancelButton: false,
            showClose: false,
            type: "error",
          },
        ).then(async () => {
          window.localStorage.removeItem("token");
          await router.push("/login");
        });
      } else {
        this.menu = data;
      }
    },
    async setActive(menu: Menu) {
      this.defaultActive = menu.path;
      const find = this.history.find(item => item.id == menu.id);
      if (!find) {
        this.history.push(menu);
      }
    },
    setDefaultActive(path: string) {
      this.defaultActive = path;
      const menu = this.getMenuList.find(item => item.path == path) as any;
      if (menu && path != "/home") {
        const find = this.history.find(item => item.id == menu.id);
        if (!find) {
          this.history.push(menu);
        }
      }
    },
    close(activePath: string) {
      const tags: Menu[] = JSON.parse(JSON.stringify(this.history));
      const activeIndex = tags.findIndex(value => value.path === this.defaultActive);
      const index = tags.findIndex(item => item.path == activePath);
      this.history.splice(index, 1);

      if (activeIndex === index) {
        let path = "/home";
        if (index > 0) {
          path = this.history[index - 1].path;
        }
        router.push(path).then(() => {
          this.defaultActive = path;
        });
      }
    },
    async closeByType(type: "all" | "this" | "other" | "left" | "right", path?: string) {

      let defaultActive = (path ? path : this.defaultActive) as string;
      const tags: Menu[] = JSON.parse(JSON.stringify(this.history));
      const activeIndex = tags.findIndex(value => value.path === this.defaultActive);
      const defaultActiveIndex = tags.findIndex(value => value.path === defaultActive);

      switch (type) {
        case "all":
          this.history = [];
          this.setDefaultActive("/home");
          await router.push("/home");
          break;
        case "this":
          if (defaultActive && defaultActive != "/home") {
            this.close(<string>defaultActive);
          }
          break;
        case "other":
          if (defaultActive == "/home") {
            console.log(1);
            this.setDefaultActive("/home");
            this.history = [];
            await router.push("/home");
          } else {
            const find = this.history.find(item => item.path == defaultActive);
            if (defaultActive != this.defaultActive) {
              this.setDefaultActive(<string>find?.path);
              await router.push(<string>find?.path);
            }
            // @ts-ignore
            this.history = [find];
          }
          break;
        case "left":
          this.history = [];
          tags.forEach((value, index, array) => {
            if (index >= defaultActiveIndex) {
              this.history.push(value);
            }
          });

          if (defaultActive != this.defaultActive && defaultActiveIndex > activeIndex) {
            this.setDefaultActive(defaultActive);
            await router.push(defaultActive);
          }
          break;
        case "right":
          this.history.splice(defaultActiveIndex + 1, this.history.length - defaultActiveIndex);

          if (defaultActive != this.defaultActive && defaultActiveIndex < activeIndex) {
            this.setDefaultActive(defaultActive);
            await router.push(defaultActive);
          }

          break;
      }
    },
  },
});
